'''
Created on 11.11.2009

@author: Drago
'''

from pygs.logger import logger
from pygs.services.security.securityPersistence import SecurityPersistence
from pygs.services.security.securityTokenData import TokenData
import MySQLdb

class SecurityPersistenceInMySQLDB(SecurityPersistence):
    '''
    classdocs
    '''

    def startup(self, params = None):
        SecurityPersistence.startup(self, params)
        assert params or self.params, 'Must define params for startup service!'
        if params:
            self.params = params
        # open connection to DB with params
        host = self.params["MySQL.host"]
        port = self.params["MySQL.port"]
        user = self.params["MySQL.user"]
        passwd = self.params["MySQL.passwd"]
        db = self.params["MySQL.db"]
        self.con = MySQLdb.connect(host=host, port=port, user=user, passwd=passwd, db=db)
        self.con.autocommit(1)
        logger.log("Connection to MySQL established. Host = '%s', port = '%s', user = '%s'." %
            (host, port, user))

    def shutdown(self):
        SecurityPersistence.shutdown(self)
        self.con.close()
        logger.log("Connection to MySQL closed.")

    def saveToken(self, token, tokenData):
        try:
            query = r"CALL `pygs`.`SaveUserToken`(%s, '%s', '%s');" % \
                (tokenData.userId, token, tokenData.expirationDate)
            logger.debug("Save token query: \n%s" % query)
            self.con.query(query)
        except:
            return False
        return True
    
    def loadTokenData(self, token):
        cursor = self.con.cursor()
        query = r"CALL `pygs`.`GetTokenInfo`('%s');" % (token)
        logger.debug("Get token info query: \n%s" % query)
        cursor.execute(query)
        result = cursor.fetchone()
        
        if not result:
            return None

        # make TokenData from query result
        tokenData = TokenData(result[0], result[1], result[2])
        return tokenData
    
    def deleteToken(self, token):
        # get user ID
        cursor = self.con.cursor()
        query = "SELECT  `pygs`.`GetUserIDByToken`('%s');" % token
        logger.debug("Get user by token query: \n%s" % query)
        cursor.execute(query)
        result = cursor.fetchone()
        if not result[0]:
            logger.log("User by token '%s' not found!" % token)
            return False

        # if user exists, delete his token
        userID = result[0]
        try:
            query = "CALL `pygs`.`DeleteUserSessionByToken`(%s, '%s');" % (userID, token)
            logger.debug("Delete token query: \n%s" % query)
            self.con.query(query)
            return True
        except:
            return False
    
    def getUserParams(self, userId, paramNames):
        cursor = self.con.cursor()
        query = r"CALL `pygs`.`GetUserInfoByID`(%d);" % (userId)
        logger.debug("Get user params by ID query: \n%s" % query)
        cursor.execute(query)
        result = cursor.fetchone()
        
        if not result:
            return None

        userInfo = {"userId": result[0], "userName": result[1],"passwd": result[2]}
        result = {}
        for name in paramNames:
            if userInfo.has_key(name):
                result[name] = userInfo[name]
        return result
    
    def getUserParamsByUserName(self, userName, paramNames):
        # get user ID
        cursor = self.con.cursor()
        query = ("SELECT `pygs`.`GetUserIDByName`('%s');" %
            (userName))
        logger.debug("Find user by name query: \n%s" % query)
        cursor.execute(query)
        result = cursor.fetchone()
        if not result[0]:
            return None

        # if user exists, get params by Id
        userId = result[0]        
        result = self.getUserParams(userId, paramNames)        
        return result